/*
** mysh.c for minishell2 in /home/lingla_j/work/tutorat/env
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Tue Feb 28 18:11:46 2012 julien linglain
** Last update Thu Apr 12 14:56:36 2012 julien linglain
*/

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "mysh.h"

t_cmd	g_cmd[ENVSIZE]=
  {
    {"exit", b_exit},
    {"env", my_env},
    {"setenv", my_setenv},
    {"unsetenv", my_unsetenv},
    {"cd", my_cd},
    {"pwd", b_pwd},
    {"echo", b_echo},
    {NULL, NULL}
  };

int		check_command(int bc, char **bv, char *s, t_list *envi)
{
  int		i;

  i = 0;
  while (g_cmd[i].cmd != NULL)
    {
      if (my_strcmp(g_cmd[i].cmd, bv[0]) == 0)
	{
	  g_cmd[i].ptr_func(bc, s, bv, envi);
	  return (EXIT_SUCCESS);
	}
      if (i == ENVSIZE - 2)
	exec_com(bc, bv, s, envi);
      i++;
    }
  return (EXIT_SUCCESS);
}

void		handle_sig(int signum)
{
  if (signum == SIGINT)
    my_putchar('\n');
}

void		boucle(t_list *envi, char *s, int bc, char **bv)
{
  while (42)
    {
      signal(SIGINT, handle_sig);
      prompt(envi);
      s = my_read();
      if (s != NULL)
        {
          bv = my_str_to_wordtab(s);
          bc = my_tablen(bv);
          if (bc > 0)
            {
              check_command(bc, bv, s, envi);
              free_bv(bc, bv);
            }
        }
      free(s);
    }
}

int		main(int ac, char **av, char **env)
{
  int		bc;
  char		**bv;
  char		*s;
  t_list	*envi;

  envi = xmalloc(sizeof(t_list));
  bc = 0;
  bv = NULL;
  s = NULL;
  init_env(envi, env);
  boucle(envi, s, bc, bv);
  return (EXIT_SUCCESS);
}
